package com.example.demo16_custom_detailssource.controller;

import com.example.demo16_custom_detailssource.config.MyWebAuthenticationDetails;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class VerifyCodeController {

    @Autowired
    Producer producer;

    @GetMapping("/verifyCode")
    public void verifyCode(HttpSession session, HttpServletResponse response) throws IOException {
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        session.setAttribute("verifyCode",text);
        response.setContentType("image/jpeg");
        ImageIO.write(image,"jpeg",response.getOutputStream());
    }

    @GetMapping("/details")
    public String details(){
        // 获取登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 获取当前请求的详细信息，默认 WebAuthenticationDetails，只保存了 登录用户的ip地址 和 sessionId
//        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        MyWebAuthenticationDetails details = (MyWebAuthenticationDetails) authentication.getDetails();
        System.out.println("details = " + details);
        return details.toString();
    }

}
